package com.arqui.admmon_module.server.handlers;

import java.net.UnknownHostException;
import co.edu.unal.satacredito.database.connection.AdministratorDatastoreFactory;
import co.edu.unal.satacredito.database.dao.AdministratorMongoDao;
import co.edu.unal.satacredito.database.entity.Administrator;
import co.edu.unal.satacredito.database.entity.exceptions.NonexistentEntityException;
import com.google.code.morphia.Datastore;
import com.mongodb.MongoException;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.arqui.admmon_module.client.action.GetLogin;
import com.arqui.admmon_module.client.action.GetLoginResult;
import com.google.inject.Inject;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.shared.ActionException;

public class GetLoginActionHandler implements
		ActionHandler<GetLogin, GetLoginResult> {

	private Datastore ds;
    private AdministratorMongoDao instance;
    private Administrator admin;
	private GetLoginResult result;
	
	@Inject
	public GetLoginActionHandler() {
	}

	@Override
	public GetLoginResult execute(GetLogin action, ExecutionContext context) throws ActionException {
		Boolean r = false;
		String message = "El usuario o la contraseña son incorrectos.";
		String message_null = "ingrese los datos completos";
		String message_data = "Verifique que la conexión este activada.";
		
		result = new GetLoginResult(r,message);
		
		
		
		if(action.getUser().equals(null) || action.getPassword().equals(null) || action.getUser().equals("") || action.getPassword().equals("")){
			result.setMessage(message_null);
			return result;
		}
		
		try {
			
			ds = AdministratorDatastoreFactory.createDatastore();
			instance = new AdministratorMongoDao(ds);
			admin = instance.findByUser(action.getUser());
			
		}	catch (UnknownHostException | MongoException e) {
			result.setMessage(message_data);
			return result;
		}	catch (NonexistentEntityException e) {
			result.setMessage(message);
			return result;
		}
		
		if(admin.getPassword().equals(action.getPassword())){
			result.setMessage("");
			result.setState(true);
			return result;
		}
		return result;
	}

	@Override
	public void undo(GetLogin action, GetLoginResult result,
			ExecutionContext context) throws ActionException {
	}

	@Override
	public Class<GetLogin> getActionType() {
		return GetLogin.class;
	}
}
